package com.cefa.edu.service;

import com.alibaba.fastjson.JSONObject;
import com.cefa.edu.common.ConstantProperties;
import com.cefa.edu.model.Course;
import com.cefa.edu.model.School;
import com.cefa.edu.model.User;
import com.cefa.edu.pojo.*;
import com.cefa.edu.common.TransformationUtils;
import com.cefa.edu.dao.*;
import com.cefa.edu.model.*;
import com.cefa.edu.pojo.Class;
import com.cefa.edu.pojo.Instructor;
import com.cefa.edu.util.HttpRequestUtil;
import com.cefa.edu.util.MD5Generator;
import com.cefa.edu.util.TimeUtil;
import com.google.common.base.Strings;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.regex.Pattern;

/**
 * @author huangzehui
 * @date 18-7-31 下午2:55
 */
@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    ClassMapper classMapper;
    @Autowired
    GradeMapper gradeMapper;
    @Autowired
    PhaseMapper phaseMapper;
    @Autowired
    StudentStageDataMapper studentStageDataMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    EduStageMapper eduStageMapper;
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    EducationLevelMapper educationLevelMapper;
    @Autowired
    UserOrganRoleMapper userOrganRoleMapper;
    @Autowired
    OrganRelationMapper organRelationMapper;
    @Autowired
    ConstantProperties constantProperties;

    /**
     * @aa  把 用户添加、及角色分配放入一个事务中
     * @aa add by chaijian 2018-08-14
     */

    @Transactional
    public void saveUserAndDistributeRole(Integer validateStatus, com.cefa.edu.pojo.User destUser, Integer levelId, Integer roleType) {



        //map值：1、未添加  2、已添加 未分配角色
        switch (validateStatus){
            case 1:
                //用户未添加
                //设置用户密码、密钥、所属学校
                destUser.setPassword(MD5Generator.generatorMD5(destUser.getPassword()));
                destUser.setKeyData(destUser.getPassword());//密钥与登陆密码一致  ？？？
                //学校id 由前端作为参数传递过来
                //判断若学校id 为空，默认是1
                if(destUser.getSchoolId()==null||destUser.getSchoolId()==0){
                    destUser.setSchoolId(1);
                }

                //执行用户入库操作
                if(roleType==6){
                    //添加监护人 涉及到监护的学生
                    this.saveUserGuardian(destUser);
                }else {
                    this.saveUserNotGuardian(destUser);
                }
                //分配角色
                //int res= this.saveUserOrganRole(destUser,levelId,roleType);
                break;
            case 2:
                //已添加 未分配角色
                //使用身份证号获取 已入库的用户
                destUser= this.getUserByIdCode_new(destUser.getIdCode());
                break;
        }
        //分配角色
        int res= this.saveUserOrganRole(destUser,levelId,roleType);
    }

    /**
     * @aa 添加userOrganRole关系数据
     * @aa add by chaijian 2018-08-13
     */
    public Integer saveUserOrganRole(com.cefa.edu.pojo.User user, Integer organId, Integer roleType){
        //organId不同 sql不同
        Map<String,Object> paramMap=new HashMap<String,Object>();//封装入库的参数
        Map<String,Object>  classRelMap=null;
        Map<String,Object>  phaseRelMap=null;

        paramMap.put("userId",user.getId());
        paramMap.put("schoolId",user.getSchoolId());
        switch (roleType){
            case 1:
                break;
            case 2:
                //教育阶段管理者
                paramMap.put("phaseId",organId);
                paramMap.put("roleType",roleType);
                paramMap.put("duties",user.getDuties());
                userOrganRoleMapper.saveUserOrganRoleForPhaseManager(paramMap);
                break;
            case 3:
                //根据organId此时是年级id 获取对应的学段id
                phaseRelMap=organRelationMapper.getOrganRelationBySchoolIdAndGradeId(organId,user.getSchoolId());
                if(phaseRelMap!=null &&phaseRelMap.size()>0 ){
                    //获取教育阶段id
                    Integer phaseId=phaseRelMap.get("phaseId")!=null?Integer.parseInt(phaseRelMap.get("phaseId").toString()):0;
                    paramMap.put("phaseId",phaseId);
                    paramMap.put("gradeId",organId);
                    paramMap.put("roleType",roleType);
                    paramMap.put("duties",user.getDuties());
                    userOrganRoleMapper.saveUserOrganRoleForGradeManager(paramMap);
                }else{
                    throw new RuntimeException("参数不对，请核对参数！");
                }

                break;
            case 4: case 6:case 7:
                //班主任 监护人 学生 用户角色机构最小节点为班级
                //根据organId此时是班级id 获取对应的教育阶段id、年级id
                classRelMap=organRelationMapper.getOrganRelationBySchoolIdAndClassId(organId,user.getSchoolId());
                Integer phaseId=0;
                Integer gradeId=0;
                if(classRelMap!=null&&classRelMap.size()>0){
                    //获取该班级对应的年级id 和学习阶段id
                    phaseId=classRelMap.get("phaseId")!=null?Integer.parseInt(classRelMap.get("phaseId").toString()):0;
                    gradeId=classRelMap.get("gradeId")!=null?Integer.parseInt(classRelMap.get("gradeId").toString()):0;
                    paramMap.put("phaseId",phaseId);
                    paramMap.put("gradeId",gradeId);
                    paramMap.put("classId",organId);
                    paramMap.put("roleType",roleType);
                    userOrganRoleMapper.saveUserOrganRoleForDirector(paramMap);
                }else{
                    throw new RuntimeException("参数不对，请核对参数！");
                }

                //若添加的时学生用户 向学生学习阶段数据表添加数据
                if(7==roleType){

                    Map<String,Object> studentStageMap=new HashMap<String,Object>();
                    //根据班级id 获取对应的班级数据
                    Class classBean=classMapper.getClassById(organId);
                    //根据年级id 获取对应的班级数据
                    Grade gradeBean=gradeMapper.getGradeById(gradeId);
                    //根据学习阶段id 获取对应的班级数据
                    Phase phaseBean=phaseMapper.getPhaseById(phaseId);

                    /**
                     * @aa 根据学生id,学习阶段id,学校id 判断该学生的学校教育阶段数据是否已经入库
                     * @aa add by chaijian 2018-08-14
                     */
                    int count=studentStageDataMapper.getCountFormStudentStageDataTable(user.getId(),phaseBean.getId(),user.getSchoolId());
                    if(count<=0){
                        //获取当前年份
                        Calendar calendar=Calendar.getInstance();
                        calendar.setTime(new Date());
                        int year= calendar.get(Calendar.YEAR);

                        //把获取到的数据封装到map中
                        studentStageMap.put("userId",user.getId());
                        studentStageMap.put("className",classBean.getClassName());
                        studentStageMap.put("gradeName",gradeBean.getGradeName());
                        studentStageMap.put("phaseName",phaseBean.getPhaseName());

                        studentStageMap.put("startYear",year);//int
                        studentStageMap.put("schoolId",user.getSchoolId());
                        studentStageMap.put("level",phaseId==1?4:(phaseId==2?6:((phaseId==3||phaseId==4)?3:0)));//int 有学习阶段判断
                        studentStageMap.put("stageId",phaseId);
                        studentStageMap.put("stageType",roleType);
                        studentStageMap.put("gradeId",gradeId);

                        //执行数据存储操作
                        studentStageDataMapper.saveStudentStageData(studentStageMap);
                    }
                }

                break;
            case 5:
                //教师
                //根据organId此时是班级id 获取对应的教育阶段id、年级id
                classRelMap=organRelationMapper.getOrganRelationBySchoolIdAndClassId(organId,user.getSchoolId());
                if(classRelMap!=null &&classRelMap.size()>0){
                    //获取该班级对应的年级id 和学习阶段id
                    phaseId=classRelMap.get("phaseId")!=null?Integer.parseInt(classRelMap.get("phaseId").toString()):0;
                    gradeId=classRelMap.get("gradeId")!=null?Integer.parseInt(classRelMap.get("gradeId").toString()):0;
                    Integer classId=classRelMap.get("classId")!=null?Integer.parseInt(classRelMap.get("classId").toString()):0;
                    paramMap.put("phaseId",phaseId);
                    paramMap.put("gradeId",gradeId);
                    paramMap.put("classId",classId);
                    paramMap.put("courseId",organId);
                    paramMap.put("roleType",roleType);
                    userOrganRoleMapper.saveUserOrganRoleForInstructor(paramMap);
                }else{
                    throw new RuntimeException("参数不对，请核对参数！");
                }

                break;
        }
        return 0;
    }

    /**
     * @aa 添加监护人用户数据
     * @aa add by chaijian 2018-08-14
     */
    public Integer saveUserGuardian(com.cefa.edu.pojo.User destUser){
        return userMapper.saveUserGuardian(destUser);
    }

    /**
     * @aa 添加非任课教师用户数据
     * @aa add by chaijian 2018-08-13
     * @return
     */
    public Integer saveUserNotGuardian(com.cefa.edu.pojo.User destUser){
        return userMapper.saveUserNotGuardian(destUser);
    }


    /**
     * @aa 根据身份证号获取对应的用户
     * @aa add by chaijian 2018-08-13
     */
    public com.cefa.edu.pojo.User getUserByIdCode_new(String idCode){
        return userMapper.getUserByIdCode_new(idCode);
    }

    /**
     * @aa 根据学生毕业年份和学生名称 获取对应的毕业生信息
     * @aa 按照学生名称排序
     * @aa add by chaijian 2018-08-03
     */
    public  List<HashMap<String,Object>> getGraduates(Integer schoolId,Integer graduatedYear, String name,Integer pageNo,Integer pageSize){
        //组织检索条件
        StringBuffer retrialSb=new StringBuffer(" WHERE u.id = s.user_id");
        retrialSb.append(" AND s.school_id = ");//学校id 默认为1
        retrialSb.append(schoolId);
        retrialSb.append(" AND s.graduate=1");//获取已毕业学生

        if(graduatedYear!=null &&graduatedYear!=0){
            retrialSb.append(" AND s.end_year = "+graduatedYear+"");
        }
        if(StringUtils.isNotBlank(name)){
            retrialSb.append(" AND u.name like '%"+name+"%'");
        }

        //设置排序条件
        retrialSb.append(" ORDER BY s.start_year desc,s.education_stage_name");

        if(pageNo==null&&pageSize==null ){
           pageNo=0;
           pageSize=10;

        }else if(pageNo==null &&pageSize!=null){
            pageNo=0;

        }else if(pageNo!=null && pageSize==null){
            pageSize=10;
            pageNo=(pageNo-1)*pageSize;

        }else if(pageNo!=null && pageSize!=null){
            pageNo=(pageNo-1)*pageSize;
        }

        //设置 分页检索条件
        retrialSb.append(" LIMIT ");
        retrialSb.append(pageNo+", ");
        retrialSb.append(pageSize);
        List<HashMap<String,Object>> graduatesList=eduStageMapper.getGraduates(retrialSb.toString());

        return graduatesList;
    };

//    /**
//     * 添加用户，包括各种角色用户的添加 角色类型：1、管理者 2、班主任、3、教师、4、监护人、5、学生
//     * @param user
//     * @param roleType
//     * @param levelId
//     * @param courseId
//     */
//    @Transactional("transactionManager")
//    public void insertUserRole(User user, Integer roleType, Integer levelId, Integer courseId) {
//        //1、首先检查是否该用户已存在，如果已存在，则不做用户保存操作
//        User u= userMapper.getUserByIdCode(user.getIdCode());
//        //3、根据角色类型，查询角色id
//        Role role = userMapper.getRoleByType(roleType);
//        Integer userId;
//        if(u==null){
//            //2、保存用户数据
//            user.setPassword(MD5Generator.generatorMD5(user.getPassword()));
//            userMapper.insertUser(user);
//            userId=user.getId();
//            if("student".equals(role.getRoleName())){//如果是学生的话，年级第一次录入的时候会保存阶段性数据信息,正常情况，在一个教育阶段的年级里学生会自动升级，不存在一个教育阶段添加多次该学生的信息
//                EducationLevel educationLevel3=  educationLevelMapper.getEducationLevelById(levelId);
//                EducationLevel educationLevel2=  educationLevelMapper.getEducationLevelById(educationLevel3.getPId());
//                EducationLevel educationLevel1=  educationLevelMapper.getEducationLevelById(educationLevel2.getPId());
//                StudentStageData studentStageData =new StudentStageData();
//                studentStageData.setClassName(educationLevel3.getName());
//                studentStageData.setGradeName(educationLevel2.getName());
//                studentStageData.setEducationStageName(educationLevel1.getName());
//                studentStageData.setSchoolId(user.getSchoolId());
//                studentStageData.setEducationStageId(educationLevel1.getId());
//                studentStageData.setStartYear(educationLevel2.getGradeDate());
//                studentStageData.setUserId(user.getId());
//                studentStageData.setLevel(educationLevel1.getSort());
//                userMapper.insertStudentStageData(studentStageData);
//            }
//        }else{
//            userId=u.getId();
//        }
//
//        //4、保存用户角色关联数据,如果已经有这个角色就没必要再保存了
//        if(userRoleMapper.getUserRole(userId,role.getId())==0){
//            userMapper.insertUserRole(userId,role.getId());
//        }
//        //5、 如果是管理者、班主任、老师、学生 需要保存 用户层级关联数据
//        if(!"guardian".equals(role.getRoleName())&&educationLevelMapper.getUserLevel(userId,levelId)==0){//只有监护人不需要层级归属关系，但是需要学生id,另外如果在该层已经有用户层级关联数据，就无需重复保存
//            userMapper.insertUserLevel(userId,levelId,roleType,user.getSchoolId(),user.getDuties(),0);
//        }
//        //6、如果是班主任或者老师，需要添加任课教师表（因为一个老师可以在多个班级任课，一个班主任也可能带多个班级）
//        if("director".equals(role.getRoleName())||"instructor".equals(role.getRoleName())){
//            int isDirector="director".equals(role.getRoleName())?1:0;
//            userMapper.insertInstructor(userId,courseId,levelId,isDirector);
//        }
//        //7、如果选择是班主任，则需要保存班主任信息 和教师用户关联起来
////        if("director".equals(role.getRoleName())){
////            userMapper.insertDirector(userId,levelId);
////        }
//
//    }

    @Transactional("transactionManager")
    public void insertCourse(Course course) {
        courseMapper.insertCourse(course);
    }

    /**
     * 对管理者提添加用户重复判断，需要根据levelid查询是否重复
     * @param levelId
     * @param idCode
     * @return
     */
    @Transactional("transactionManager")
    public int  findUserByLevelIdAndIdCode(Integer levelId ,String idCode) {
        return  userMapper.findUserByLevelIdAndIdCode(levelId,idCode);
    }

    /**
     * 对任课老师而言查询重复判断
     * @param levelId
     * @param idCode
     * @param courseId
     * @return
     */
    @Transactional("transactionManager")
    public int findUserByLevelIdWithInstructor(Integer levelId ,String idCode,Integer courseId) {
        return  userMapper.findUserByLevelIdWithInstructor(levelId,idCode,courseId);
    }

    /**
     * 对班主任而言查询重复判断
     * @param levelId
     * @param idCode
     * @return
     */
    @Transactional("transactionManager")
    public int findUserByLevelIdWithDirector(Integer levelId ,String idCode,Integer director) {
        return  userMapper.findUserByLevelIdWithDirector(levelId,idCode,director);
    }

    @Transactional("transactionManager")
    public List<Instructor> findDirectorByLevelId(Integer levelId) {
        return  userMapper.findDirectorByLevelId(levelId);
    }
    @Transactional("transactionManager")
    public List<Course> findCourseListByLevelId(Integer levelId) {
        return  courseMapper.findCourseListByLevelId(levelId);
    }
    @Transactional("transactionManager")
    public int  getUserCount(Integer levelId) {
        return  userMapper.getUserCount(levelId);
    }

    @Transactional("transactionManager")
    public int  updateCourseStatus(Integer courseId) {
        return  courseMapper.updateCourseStatus(courseId);
    }


    @Transactional("transactionManager")
    public School getSchool(Integer id) {
        return  userMapper.getSchool(id);
    }

    @Transactional("transactionManager")
    public int  findUserBylevelId(Integer userId,Integer levelId) {
        return  userRoleMapper.findUserBylevelId(userId,levelId);
    }
    @Transactional("transactionManager")
    public List<User>  getManagerByLevel(Integer levelId) {
        return  userMapper.getManagerByLevel(levelId);
    }
    @Transactional("transactionManager")
    public List<User>  getUserRoleByType(Integer type) {
        return  userRoleMapper.getUserRoleByType(type);
    }
    @Transactional("transactionManager")
    public List<User>  getStudentByLevelId(Integer type,Integer levelId) {
        return  userMapper.getStudentByLevelId(type,levelId);
    }

    @Transactional("transactionManager")
    public Course getCourseById(Integer id) {
        return  courseMapper.getCourseById(id);
    }

    /**
     * 验证用户名称并自动给出命名规范给的用户名
     * @param add by chaijian 20180903
     * @return
     */
    @Transactional("transactionManager")
    public String getUserNamePi(String userName){
        String userNamePi=TransformationUtils.getPingYin(userName);
        List<com.cefa.edu.pojo.User> users=userMapper.getUserPi(userNamePi);

        if(users!=null&&users.size()>=1){

            for(com.cefa.edu.pojo.User user:users){
                String userName2=user.getUserName();

                if(userName2.length()>6){
                    //长度大于六位 判断后六位是否是数字
                    String suffix=userName2.substring(userName2.length()-6);
                    try{
                        //不出错 用户有后六位数
                        int intSuffix= Integer.parseInt(suffix);
                        if(userName2.substring(0,userName2.length()-6).equals(userNamePi)){
                            String strNm=userName2.substring(userName2.length()-6,userName2.length());
                            Pattern pattern = Pattern.compile("[0-9]*");
                            boolean falt=pattern.matcher(strNm).matches();
                            if(falt){
                                String newStr = strNm.replaceFirst("^0*", "");
                                String str = String.format("%06d",  Integer.parseInt(newStr)+1);
                                userNamePi=userNamePi+str;
                            }else{
                                userNamePi=userNamePi+"000001";
                            }
                            break;
                        }
                    }catch(Exception e){
                        if(userName2.equals(userNamePi)){
                            userNamePi=userNamePi+"000001";
                            break;
                        }
                    }

                }else{
                    //长度小于六位
                    if(userName2.equals(userNamePi)){
                        userNamePi=userNamePi+"000001";
                        break;
                    }
                }
            }// for(com.cefa.edu.pojo.User user:users)
        }

        return userNamePi;
    }

    /**
     * 验证用户名称并自动给出命名规范给的用户名
     * @param userName
     * @return
     */
    @Transactional("transactionManager")
    public String getUserNamePi2(String userName){
        String userNamePi=TransformationUtils.getPingYin(userName);
        List<com.cefa.edu.pojo.User> users=userMapper.getUserPi(userNamePi);
        if(users!=null&&users.size()>=1){
            String userName2=users.get(0).getUserName();
            if(userName2.length()>6){
                String strNm=userName2.substring(userName2.length()-6,userName2.length());
                Pattern pattern = Pattern.compile("[0-9]*");
                boolean falt=pattern.matcher(strNm).matches();
                if(falt){
                    String newStr = strNm.replaceFirst("^0*", "");
                    String str = String.format("%06d",  Integer.parseInt(newStr)+1);
                    userNamePi=userNamePi+str;
                }else{
                    userNamePi=userNamePi+"000001";
                }
            }else{
                userNamePi=userNamePi+"000001";
            }
        }
        return userNamePi;
    }

    @Transactional("transactionManager")
    public void updateUserById(com.cefa.edu.pojo.User user, Integer roleType, Integer levelId) {
        //userMapper.updateUserById(user.getId(),user.getName(),user.getIdCode());
        /*
        if(user.getPassword()!=null&&!"".equals(user.getPassword())){
            user.setPassword(MD5Generator.generatorMD5(user.getPassword()));
            userMapper.updateUserById3(user);
        }else{
           userMapper.updateUserById2(user);
        }*/
        if(user.getPassword()!=null&&!"".equals(user.getPassword())) {
            user.setPassword(MD5Generator.generatorMD5(user.getPassword()));
        }
        userMapper.updateUserById4(user);

        // userOrganRoleMapper.updateOrganRelationByIdAndRoleType(user.getId(),roleType,user.getDuties());
     // userOrganRoleMapper.updateUserOrganRoleWithUserUpdate(user,roleType,levelId,getUpdatUserOrganRoleSqlVar(user,roleType,levelId));
        user.setLevelId(levelId);
        user.setRoleType(roleType);
        if(roleType==2){
            userOrganRoleMapper.updateUserOrganRoleForPhaseManager(user.getDuties(),user.getId(),user.getLevelId());
        }
        if(roleType==3){
            userOrganRoleMapper.updateUserOrganRoleForGradeManager(user.getDuties(),user.getId(),user.getLevelId());
        }
        if(roleType==4){
            if(user.getCourseId()!=null &&user.getCourseId()!=0){
                userOrganRoleMapper.updateUserOrganRoleForInstructor(user.getCourseId(),user.getRoleType(),user.getId(),user.getLevelId());
            }else {
                userOrganRoleMapper.updateUserOrganRoleForDirector(user.getRoleType(),user.getId(),user.getLevelId());
            }
        }
        if(roleType==5){
            userOrganRoleMapper.updateUserOrganRoleForInstructor(user.getCourseId(),user.getRoleType(),user.getId(),user.getLevelId());
        }
    }


    @Transactional("transactionManager")
    public com.cefa.edu.pojo.User getUserById(Integer userId) {
        return userMapper.getUserById(userId);
    }
    @Transactional("transactionManager")
    public  Map<String,Object> deleteUser(Map<String,Object> result,Integer userId,Integer levelId,Integer roleType,Integer classId) {
        if(userId==0||userId==null || roleType==0||roleType==null){
            result.put("msge","删除用户时，用户编号和角色编号不可为空！");
            return result;
        }

        if(roleType==2){//管理者
            if(levelId==0||levelId==null){
                result.put("msg","删除教育阶段管理者时，管理者所在教育阶段编号不可为空！");
            }else{
                userMapper.deletePhase(userId,roleType,levelId);
            }

        }else if(roleType==3){
            if(levelId==0||levelId==null){
                result.put("msg","删除年级管理者时，管理者所在年级编号不可为空！");
            }else{
                userMapper.deleteGrade(userId,roleType,levelId);
            }

        }else if(roleType==4){
            if(classId==0||classId==null){
                result.put("msg","删除授课老师时，该老师所在的班级和科目编号不可为空！");
                return result;
            }
                //若是班主任  判断该老师是否有教课 班主任   教一班 数学  教二班 数学
                List<Integer> courseIdList=userOrganRoleMapper.getCourseIdList(userId,classId,roleType);
                if(courseIdList!=null && courseIdList.size()>0){
                    if(levelId==0||levelId==null){
                        result.put("msg","删除教课的班主任时，该老师所在的科目编号不可为空！");
                        return result;
                    }
                        //有授课 levelId科目编号
                        userMapper.deleteInstructor(userId,roleType,levelId,classId);
                }

                   //未授课 levelId科目编号
                    userMapper.deleteClass(userId,roleType,classId);

        }else if(roleType==5){
            if(classId==0||classId==null||levelId==0||levelId==null){
                result.put("msg","删除授课老师时，该老师所在的班级和科目编号不可为空！");
                return result;
            }
                userMapper.deleteInstructor(userId,roleType,levelId,classId);
        }else if(roleType==6){//学生或家长或班主任
            if(levelId==0||levelId==null){
                result.put("msg","删除学生或监护人时，该班级编号不可为空！");
                return result;
            }
            userMapper.deleteClass(userId,roleType,levelId);
        }else if(roleType==7){
            //删除该学生对应的教育阶段数据
            OrganRelation organRelation=organRelationMapper.findOrganRelationByClassId(levelId);
            if(organRelation!=null&&organRelation.getPhaseId()!=null){
                eduStageMapper.deleteEducationStage(userId,organRelation.getPhaseId());
            }
            //删除学生与监护人的关系
            Map<String,Object> guardianMap= userMapper.getGuardianByStudentId(userId);
            if(guardianMap!=null&&guardianMap.size()>0){
                Integer guardianId=guardianMap.get("id")!=null?Integer.parseInt(guardianMap.get("id").toString()):null;
                if(guardianId!=null){
                    int res=userMapper.removeRelationshipOfguardianStuden(guardianId);
                }
            }

            //删除学生角色关系
            userMapper.deleteClass(userId,roleType,levelId);
        }
        return result;
    }
    @Transactional("transactionManager")
    public  void  updateClass(Integer classId,String className) {
       classMapper.updateClass(classId,className);
    }



    /**
     * @aa 获取当前系统最早毕业生毕业年份
     * @aa add by chaijian 2018-08-16
     */
    public Integer getMinGraduatedYear() {

      return studentStageDataMapper.getMinGraduatedYear();
    }

    @Transactional
    public  Map<String,Object>  saveUserAndDistributeRole2( com.cefa.edu.pojo.User user, Integer levelId, Integer roleType,Integer courseId) {
        if(Strings.isNullOrEmpty(user.getPassword())){
            user.setPassword("123456");
        }
        com.cefa.edu.pojo.User destUser = this.getUserByIdCode_new(user.getIdCode());
        Integer userId;
        Map<String,Object> idCodeUserMap=new HashMap<>();
        if(destUser==null){
            String jsonData=HttpRequestUtil.sendPost(constantProperties.newwallet,"{}","UTF-8");
            String mnemonic=JSONObject.parseObject(JSONObject.parseObject(jsonData).get("msg").toString()).get("mnemonic").toString();
            String path=JSONObject.parseObject(JSONObject.parseObject(jsonData).get("msg").toString()).get("path").toString();
            String prikey=JSONObject.parseObject(JSONObject.parseObject(jsonData).get("msg").toString()).get("prikey").toString();
            String address=JSONObject.parseObject(JSONObject.parseObject(jsonData).get("msg").toString()).get("address").toString();
            String checksum=JSONObject.parseObject(JSONObject.parseObject(jsonData).get("msg").toString()).get("checksum").toString();
            user.setKeyData(prikey);
            user.setDerivePath(path);
            user.setMnemonic(mnemonic);
            user.setAddress(address);
            user.setChecksum(checksum);
            List<com.cefa.edu.pojo.User> userList=userMapper.getUserListBySchoolId(user.getSchoolId());
            JSONObject jsonObject3= new JSONObject();
            jsonObject3.put("stuAddress",address);
            jsonObject3.put("eduPrikey",userList.get(0).getKeyData());
            String studentData=HttpRequestUtil.sendPost(constantProperties.deployfile,jsonObject3.toJSONString(),"UTF-8");
            JSONObject json=JSONObject.parseObject(JSONObject.parseObject(studentData).get("msg").toString());
            user.setFileAddress(json.get("fileAddress").toString());
            user.setVerificationAddress(json.get("verificationAddress").toString());
            user.setPassword(MD5Generator.generatorMD5(user.getPassword()));
            userMapper.insertUser(user);
            userId=user.getId();
        }else {
            // 获取 用户名 用户中文名称
            idCodeUserMap.put("msg","该身份证号已使用");
            idCodeUserMap.put("name",destUser.getName());
            idCodeUserMap.put("userName",destUser.getUserName());
            userId=destUser.getId();
        }
        //保存用户角色权限表数据
        UserOrganRole userOrganRole = new UserOrganRole();
        userOrganRole.setUserId(userId);
        userOrganRole.setSchoolId(user.getSchoolId());
        userOrganRole.setRoleType(roleType);
        userOrganRole.setDuties(user.getDuties());
        Map<String,Object>  classRelMap=null;
        Map<String,Object>  phaseRelMap=null;
        Integer phaseId=0;
        Integer gradeId=0;
        if(roleType==constantProperties.admin||roleType==constantProperties.phasemanager){
            userOrganRole.setPhaseId(levelId);
            userOrganRole.setGradeId(0);
            userOrganRole.setClassId(0);
            userOrganRole.setCourseId(0);
        }else if(roleType==constantProperties.grademanager){
            phaseRelMap=organRelationMapper.getOrganRelationBySchoolIdAndGradeId2(levelId,user.getSchoolId());
            if(phaseRelMap!=null && phaseRelMap.size()>0){
              phaseId= phaseRelMap.get("phaseId")!=null?Integer.parseInt(phaseRelMap.get("phaseId").toString()):0;

            phaseId=Integer.parseInt(phaseRelMap.get("phaseId").toString());
            userOrganRole.setPhaseId(phaseId);
            userOrganRole.setGradeId(levelId);
            userOrganRole.setClassId(0);
            userOrganRole.setCourseId(0);
            }
        }else if(roleType==constantProperties.instructor){
            classRelMap=organRelationMapper.getOrganRelationBySchoolIdAndClassId2(levelId,user.getSchoolId());
            //phaseId gradeId classId
            phaseId=Integer.parseInt(classRelMap.get("phaseId").toString());
            gradeId=Integer.parseInt(classRelMap.get("gradeId").toString());
            userOrganRole.setPhaseId(phaseId);
            userOrganRole.setGradeId(gradeId);
            userOrganRole.setClassId(levelId);
            userOrganRole.setCourseId(courseId);
        }else{
            classRelMap=organRelationMapper.getOrganRelationBySchoolIdAndClassId2(levelId,user.getSchoolId());
            phaseId=Integer.parseInt(classRelMap.get("phaseId").toString());
            gradeId=Integer.parseInt(classRelMap.get("gradeId").toString());
            userOrganRole.setPhaseId(phaseId);
            userOrganRole.setGradeId(gradeId);
            userOrganRole.setClassId(levelId);
            userOrganRole.setCourseId(0);
            if(roleType==constantProperties.student){
                Class classBean=classMapper.getClassById2(levelId);
                //根据年级id 获取对应的班级数据
                Grade gradeBean=gradeMapper.getGradeById2(gradeId);
                //根据学习阶段id 获取对应的班级数据
                Phase phaseBean=phaseMapper.getPhaseById2(phaseId);
                Map<String,Object> studentStageMap=new HashMap<String,Object>();
                studentStageMap.put("userId",userId);
                studentStageMap.put("className",classBean.getClassName());
                studentStageMap.put("gradeName",gradeBean.getGradeName());
                studentStageMap.put("phaseName",phaseBean.getPhaseName());
                studentStageMap.put("startYear",Calendar.getInstance().get(Calendar.YEAR));
                studentStageMap.put("schoolId",user.getSchoolId());
                studentStageMap.put("level",phaseBean.getGradeCount());//改正处
                studentStageMap.put("stageId",phaseId);
                studentStageMap.put("stageType",gradeBean.getType());//改正处
                studentStageMap.put("gradeId",gradeId);
                studentStageDataMapper.saveStudentStageData(studentStageMap);
            }
        }

        //add by chaijian 2018-08-31 获取科目参数 存储到关系表中
        userOrganRole.setCourseId(user.getCourseId());
        int a=userOrganRoleMapper.saveUserOrganRoleAll(userOrganRole);
        return idCodeUserMap;
    }

    /**
     * @aa 根据用户账号 获取密码
     * @aa add by chaijian 2018-08-20
     */
    public String getPasswordByUserName(String userName){
        return  userMapper.getPasswordByUserName(userName);
    }

    /**
     * @aa  根据用户账号和新密码 修改用户原密码
     * @aa add by chaijian 2018-08-20
     */
    public Integer updatePasswordByUserName(String userName ,String password ) {
        return userMapper.updatePasswordByUserName(userName,password);
    }

    /**
     * @aa 根据学生id 获取对应的监护人数据接口
     * @aa add by chaijian 2018-08-22
     * @return
     */
    public Map<String,Object> getGuardianByStudentId(Integer studentId) {
        return userMapper.getGuardianByStudentId(studentId);
    }

    /**
     * @aa 获取指定学校的所有毕业生
     * @aa add by chaijian 2018-08-24
     * @return
     */
    public Integer getAllCountOfGraduates(Integer schoolId) {
        return  userMapper.getAllCountOfGraduates(schoolId);
    }

    /**
     * @aa 获取该监护下 所监护的唯一学生id
     * @aa add by chaijian 2018-08-24
     * @return
     */
    public Integer getStudentIdByGuardianId(Integer userId) {
        return userMapper.getStudentIdByGuardianId(userId);
    }

    /**
     * @aa //判断指定的省份证号是否已使用
     * @aa add by chaijian 2018-09-04
     * @return
     */
    public boolean judgeIdCodeExistByIdCode(String idCode) {
        Integer count=userMapper.judgeIdCodeExistByIdCode(idCode);
        if(count>0){
            return true;
        }else {
            return false;
        }
    }

    public boolean getCountOfUserOrganRoleWityIdCodeAndRoleType(Integer userId, Integer roleType) {
        Integer count=userMapper.getCountOfUserOrganRoleWityIdCodeAndRoleType(userId,roleType);
        if(count>0){
            return true;
        }else {
            return false;
        }
    }

}
